<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{:lang('设置套餐利润点')}</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="__PUBLIC__/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="__PUBLIC__/font-awesome/css/font-awesome.min.css" media="all" />
    <link rel="stylesheet" href="__CSS__/admin.css" media="all">
</head>
<style>
    .addPackage{
        float: right;
        margin-top: -4px;
    }
    .fastSpec{
        margin-top: 4px;
    }
    .fastSpec:first-child{
        margin-left: 10px;
    }
    .rate_input{
        border:1px #009688 solid;
    }
</style>
<body>
<div class="layui-container" style="padding: 15px;">
    <div class="layui-row">
        <div class="layui-col-md12">
            <blockquote class="layui-elem-quote">
                <span>设置产品套餐</span>
                【<span style="{if !empty($correctTip)}color:green{else}color:red{/if}">
                    {$tipMsg|default=''}
                </span>】
                <!--<button class="layui-btn layui-btn-sm addPackage" id="addPackage">添加套餐</button>-->
            </blockquote>
            <!--套餐表单-->
            <form class="layui-form" id="packageForm" style="padding: 8px;border: 1px #eee solid;">
                <input type="hidden" id="product_id" value="{$id}">
                <div id="packageBody" >
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-inline">
                        <button class="layui-btn" lay-submit lay-filter="admin">{:lang('提交')}</button>
                        <button type="reset" class="layui-btn layui-btn-primary">{:lang('重置')}</button>
                    </div>
                </div>

            </form>
        </div>
    </div>

</div>
</body>
<script src="__PUBLIC__/layui/layui.js"></script>
<script src="__PUBLIC__/jquery/jquery.min.js"></script>
<script>
    layui.use(['layer', 'form'], function() {
        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form;

        //提交表单
        form.on('submit(admin)', function(data) {
            var id = $("#product_id").val(); //产品ID
            var data = [];
            var packageChild = $(".packageChild");
            var errMsg = '';
            for(var i = 0; i < packageChild.length; i++) {
                var datas = {};
                var datal = [];

                var specsChild = $(packageChild[i]).find(".specsChild tr");
                for(var k = 0; k < specsChild.length; k++) {
                    var datass = {};
                    var specs_id = $(specsChild[k]).find("input[name=specs_id]").val();
                    var salePrice = $(specsChild[k]).find("input[name=person_price]").val();
                    if(specs_id) {
                        datass.specs_id = specs_id;
                    }
                    if(salePrice!=undefined && salePrice!='' && salePrice!=0) {
                        datass.salePrice = salePrice;
                    }
                    var bdj_rate = $(specsChild[k]).find("input[name=bdj_rate]").val();
                    if(parseInt(bdj_rate) < 0 || parseInt(bdj_rate) > 99){layer.msg('利润点设置请输入0-99的数字！');return false;}
                    datass.bdj_rate = bdj_rate;
                    datal.push(datass);
                }
                var package_id = $(packageChild[i]).find("input[name=package_id]").val();
                if(package_id) {
                    datas.package_id = package_id;
                }
                datas.specsdata = datal;

                data.push(datas);
                console.log(data);
            }
            if(data.length<1){layer.msg('请先添加套餐内容');return false;}

            $.ajax({
                url: "{:url('admin/product/setBasePackageRate')}",
                data: {
                    id: id,
                    data: data
                },
                type: 'post',
                async: false,
                success: function(res) {
                    layer.msg(res.msg);
                    if(res.code == 1) {
                        setTimeout(function() {
                            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                            parent.layer.close(index); //再执行关闭
                        }, 1500)
                    }
                }
            });
            return false;
        })
    });
</script>

<script>
    // $("#addPackage").on("click", function() {
    //     addPackage();
    // });
    //删除套餐
    $(document).on("click", ".delPackage", function() {
        var that = this;
        var id = $(that).attr("data-id");
        if(id=='' || id==undefined){
            var child = $(that).parent(".packageChild");
            child.remove();
        }else{
            layer.confirm('删除已有套餐会删除相关的价格配置<br>是否确认删除？',function(){
                $.post("/admin/product/delBasePackage",{id:id},function(data){
                    if(data.code==200){
                        var child = $(that).parent();
                        child.remove();
                        layer.msg("{:lang('删除成功')}");
                    }else{
                        layer.msg("{:lang('删除失败')}");
                    }
                },'json')
            })
        }
    });
    //删除规格
    $(document).on("click", ".delSpecs", function() {
        var that = this;
        var id = $(that).attr("data-id");
        if(id=='' || id==undefined){
            var child = $(that).parent().parent();
            child.remove();
        }else{
            layer.confirm('删除已有规格会删除相关的价格配置<br>是否确认删除？',function(){
                $.post("/admin/product/delBaseSpecs",{id:id},function(data){
                    if(data.code==200){
                        var child = $(that).parent().parent();
                        child.remove();
                        layer.msg("{:lang('删除成功')}");
                    }else{
                        layer.msg("{:lang('删除失败')}");
                    }
                },'json')
            })
        }
    });
    //添加规格
    $(document).on("click", ".addSpecs", function() {
        var html = addSpecs();
        $(this).siblings('.childs').find('.specsChild').append(html);
    })
    //快速通道添加规格
    $(document).on("click", ".fastSpec", function() {
        var spec_data = $(this).attr('data-spec');
        spec_data = spec_data.split('-');
        var specs_name = spec_data[0] || '';
        var specs_num = spec_data[1] || '';
        var minorder_num = spec_data[2] || '';
        var inc_order_num = spec_data[3] || '';
        var html = addSpecs('',specs_name,specs_num,minorder_num,inc_order_num);
        $(this).parent().parent().next().find('.specsChild').append(html);
    })
    //获取计算公式
    function getCalculationFormula(total_cost,bdj_rate){
        var result = Math.ceil(total_cost)/((100 - parseInt(bdj_rate))/100);
        return Math.ceil(result);
//        return total_cost + '/ (1-' + parseInt(bdj_rate)/100 +') = ' + Math.ceil(result);
    }
    //绑定bdj_rate
    $(document).on('input','input[name=bdj_rate]',function(){
        var value = parseInt($(this).val());
        if(value > 99 || value < 0){layer.msg('请输入0-99的数字');return false;}
        var total_cost = $(this).parent().parent().find('input[name=total_cost]').val();
        $(this).parent().next().text(getCalculationFormula(total_cost,value));
    })
    //添加规格调用方法
    function addSpecs(specs_id,specs_name,specs_num,minorder_num,inc_order_num,bdj_rate,total_cost,sale_price)
    {
        specs_id = specs_id || '';
        specs_name = specs_name || '';
        specs_num = specs_num || 99;
        minorder_num = minorder_num || 1;
        inc_order_num = inc_order_num || 1;
        bdj_rate = bdj_rate || 0;
        total_cost = total_cost || 0;
        sale_price = sale_price || 0;
        var Formula = getCalculationFormula(total_cost,bdj_rate);
        var setPriceHtml = '{if $isSetSalePrice || $product.kbx_set_market_price > 0}<td><input name="person_price" value="" type="number" lay-key="2" class="layui-input layui-col-xs5 rate_input" placeholder="'+sale_price+'"></td>\n{else}<td>'+sale_price+'</td>\n{/if}';
        var html = '' +
            ' <tr>\n' +
            '   <input type="hidden" name="specs_id" value="'+specs_id+'">\n' +
            '   <input type="hidden" name="total_cost" value="'+total_cost+'">\n' +
            '   <input type="hidden" name="sale_price" value="'+sale_price+'">\n' +
            '   <td><input readonly name="specs_name" value="'+specs_name+'" placeholder="{:lang($table_name[0])}" autocomplete="off" class="layui-input" type="text" lay-key="2"></td>\n' +
            '   <td><input readonly name="specs_num" value="'+specs_num+'" placeholder="{:lang($table_name[1])}" autocomplete="off" class="layui-input layui-col-xs5" type="number" lay-key="2"></td>\n' +
            '   <td><input readonly name="minorder_num" value="'+inc_order_num+'" placeholder="{:lang($table_name[2])}" autocomplete="off" class="layui-input layui-col-xs5" type="number" lay-key="2"></td>\n' +
            '   <td><input readonly name="inc_order_num" value="'+minorder_num+'" placeholder="{:lang($table_name[3])}" autocomplete="off" class="layui-input layui-col-xs5" type="number" lay-key="2"></td>\n' +
            '   <td>'+total_cost+'</td>\n' +
            '   <td><input name="bdj_rate" style="width: 60%;" value="'+bdj_rate+'" placeholder="{:lang($table_name[5])}" autocomplete="off" class="layui-input layui-input-inline layui-col-xs5 rate_input" min="0" max="100" step="1" type="number" lay-key="2"><span style="line-height: 40px;margin-left: 4px;">%</span></td>\n' +
            '   <td>'+Formula+'</td>\n' +
            // '   <td><span class="layui-btn layui-btn-danger layui-btn-sm delSpecs" data-id="'+specs_id+'" style="margin-top: 4px"><i class="layui-icon"></i></span></td>\n' +
            setPriceHtml +
            '</tr>';
        return html;
    }
    //添加套餐调用方法
    function addPackage(package_id,package_name){
        package_id = package_id || '';
        package_name = package_name || '';
        var setPriceHtml = "{if $isSetSalePrice}<th>建议销售价</th>{else}<th>建议销售价</th>{/if}";
//        var table_td_rate = "{if $isSetSalePrice}14%{else}16%{/if}";
        var table_td_normal = "12%";
        var table_td_rate = "14%";
        var html = '    <div class="layui-form-item packageChild" >\n' +
            '      		<label class="layui-form-label">{:lang("套餐名称")}</label>\n' +
            '      		<div class="layui-input-inline" style="width: 500px">\n' +
            '        		<div class="layui-input-inline" style="width: 400px;padding-bottom: 15px">\n' +
            '          			<input readonly name="package_name" value="'+package_name+'"  placeholder="{:lang("套餐名称")}" autocomplete="off" class="layui-input" type="text" lay-key="1">\n' +
            '          			<input name="package_id" value="'+package_id+'" type="hidden"' +
            '        		</div>\n' +
            '          </div>\n' +

            // '      		<span  class="layui-btn layui-btn-danger layui-btn-sm delPackage" data-id="'+package_id+'" style="margin-top: 4px;margin-left: 4px;float: right">{:lang("删除套餐")}</span>\n' +
            // '      		<span  class="layui-btn  layui-btn-sm addSpecs" style="margin-top: 4px;float: right">{:lang("添加规格")}</span>\n' +
            // '<div class="layui-form-item">' +
            // '<label class="layui-form-label">快速通道</label>' +
            // '<div class="layui-input-inline" style="width: 80%;">' +
            // '<a class="layui-btn layui-btn-primary fastSpec adultSpec" data-spec="成人-99-1-1">+ 成人-99-1-1</a>' +
            // '<a class="layui-btn layui-btn-primary fastSpec childrenSpec" data-spec="儿童-99-1-1">+ 儿童-99-1-1</a>' +
            // '</div>' +
            // '</div>'+
            '<div class="layui-form-item childs">'+
            '<label class="layui-form-label">&nbsp;</label>'+
            '<div class="layui-input-inline" style="width: 800px">'+
            '<table class="layui-table">'+
            '<thead><tr><th style="width:14%">{:lang($table_name[0])}</th><th style="width:'+table_td_normal+'">{:lang($table_name[1])}</th><th style="width:'+table_td_normal+'">{:lang($table_name[2])}</th><th style="width:'+table_td_normal+'">{:lang($table_name[3])}</th><th style="width:'+table_td_normal+'">{:lang($table_name[4])}</th><th style="width:'+table_td_rate+'">{:lang($table_name[5])}</th><th style="width:'+table_td_normal+'">{:lang($table_name[6])}</th>'+setPriceHtml+'</tr></thead>'+
            '<tbody class="specsChild"></tbody>'+
            '</table>'+
            '</div>'+
            '</div>'+
            '</div>';
        $("#packageBody").append(html);
        return $("#packageBody .specsChild:last");
    }
    //頁面初始化
    var packageList = {$package|json_encode};
    if(packageList.length > 0){
        $.each(packageList,function (i,v) {
            if(v.name!==''){
                var specsChild = addPackage(v.id,v.name);
                if(v.specs.length>0){
                    $.each(v.specs,function (ii,vv) {
                        var spec_html= addSpecs(vv.id,vv.name,vv.num,vv.minorder_num,vv.inc_order_num,vv.bdj_rate,vv.total_cost,vv.sale_price);
                        $(specsChild).append(spec_html);
                    })
                }
            }
        })
    }
</script>
</html>